<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class ProductsController extends AppController {

    var $name = 'Products';
    var $components = array(
        'Session', 'Alias', 'Upload', 'Resize', 'Crop', 'Watermark'
    );
    var $helpers = array(
        'Editor', 'Published', 'Category', 'Promotion'
    );
    var $uses = array(
        'Catproduct', 'Product'
    );

    function beforeFilter() {
        $this->Product->writeHotProductsSlideshow();
        $this->Product->writeHotProductsPromotion();
        $this->Product->writeHotProductsBestbuy();
        $this->Product->writeHotProductsLastest();
        $this->Product->writeHomeProductFromCategory(193, "home_quanaonam");
        $this->Product->writeHomeProductFromCategory(186, "home_quanaonu");
        $this->Product->writeHomeProductFromCategory(198, "home_quanaotreem");

        parent::beforeFilter();
    }

    function index() {

        $this->set('title_for_layout', Configure::read('site_name') . ' - Sản phẩm');
        $page = array_key_exists('page', $this->params['named']) ? $this->params['named']['page'] : 1;
        $search = !empty($this->params['form']['search']) ? $this->params['form']['search'] : false;
        $conditions = array();

        //search
        if ($search) {
            $conditions['OR'] = array(
                'Product.title LIKE' => "%$search%",
                'Product.id LIKE' => "%$search%"
             );
        }
        $this->paginate = array(
            'conditions' => $conditions,
            'limit' => Configure::read('limit_list'),
            'order' => array(
                'Product.id' => 'DESC'
            ),
        );
        $data = $this->paginate('Product');
        $this->set('image_path', Configure::read('product_image_thumb_url_path'));
        $this->set('total', $this->params['paging']['Product']['count']);
        $this->set('data', $data);
        $this->set('limit_page', $this->paginate['limit']);
        $this->set('start_page', $page);
    }

    function remove() {
        $conditions = array(
            "{$this->Product->alias}.{$this->Product->primaryKey} IN (" . implode(',', $this->params['form']['cid']) . ')'
        );
        //delete images small
        $data = $this->Product->find('all', array(
                    'conditions' => $conditions,
                    'fields' => array('Product.id', 'Product.images', 'Product.thumbnail')
                        )
        );
        foreach ($data AS $row) {
            //delete it
            if (is_file(Configure::read('product_image_thumb_absolute_path') . $row['Product']['images']) && $row['Product']['images'] != 'no_image.gif') {
                $this->Upload->delete(Configure::read('product_image_thumb_absolute_path') . $row['Product']['images']);
            }
            if (is_file(Configure::read('product_image_thumb_absolute_path') . $row['Product']['thumbnail']) && $row['Product']['thumbnail'] != 'no_image.gif') {
                $this->Upload->delete(Configure::read('product_image_thumb_absolute_path') . $row['Product']['thumbnail']);
            }
        }

        if ($this->Product->deleteAll($conditions, true)) {
            $this->Session->setFlash(sprintf("Xóa thành công %d sản phẩm", sizeof($this->params['form']['cid'])), 'msg', array(), 'msg');
        } else {
            $this->Session->setFlash('Không thể xóa', 'msg', array(), 'error');
        }
        $this->redirect(array('action' => 'index'));
    }

    function edit() {
        $this->set('title_for_layout', Configure::read('site_name') . ' - Chỉnh sữa thông tin');
        $params = array_merge($this->params['form'], $this->params['named']);
        if (isset($params['cid']) && is_array($params['cid'])) {
            $this->Product->id = $params['cid'][0];
        } else {
            $this->Product->id = array_key_exists('id', $params) ? $params['id'] : 0;
        }
        if (empty($this->data)) {
            $fields = array(
                '*'
            );
            //build status list
            $status_list = array(
                '1' => 'Còn Hàng',
                '2' => 'Call',
                '3' => 'Hết hàng',
            );
            //build size list
 
            $this->data = $this->Product->read($fields);
            $this->set('status_list', $status_list);
            $this->set('selected_product_size', explode('|', $this->data['Product']['product_size']));
            $check_thumbnail_exist = is_file(Configure::read('product_image_thumb_absolute_path') . $this->data['Product']['images']);
            $this->set('check_thumbnail_exist', $check_thumbnail_exist);
            $check_small_thumbnail_exist = is_file(Configure::read('product_image_thumb_absolute_path') . $this->data['Product']['thumbnail']);
            $this->set('check_small_thumbnail_exist', $check_small_thumbnail_exist);
            $this->set('small_thumbnail_url', Configure::read('product_image_thumb_url_path') . $this->data['Product']['thumbnail']);
            $this->set('image_url', Configure::read('product_image_thumb_url_path') . $this->data['Product']['images']);

            $this->set('description', $this->data['Product']['description']);
            $this->set('buy_description', $this->data['Product']['buy_description']);
            $this->set('cat_id', $this->data['Product']['cat_id']);
        }
    }

    function add() {
        $this->set('title_for_layout', Configure::read('site_name') . ' - thêm sản phẩm');

        //build status list
        $status_list = array(
            '1' => 'Còn Hàng',
            '2' => 'Call',
            '3' => 'Hết hàng',
        );
        $this->set('status_list', $status_list);
    }
    function crop() {
        $form = $this->params['form'];

        
        $img_300_350_filename  =   Configure::read('product_image_thumb_absolute_path') . $form['img_300_350_filename'];
        if ($this->Crop->loadImage($img_300_350_filename)) {
            $this->Crop->cropToDimensions($form['img_300_350_sx'], $form['img_300_350_sy'],$form['img_300_350_ex'],$form['img_300_350_ey']);
            $this->Crop->saveImage($img_300_350_filename);
            $this->Crop->flushImages();
        }
        $img_130_160_filename  =   Configure::read('product_image_thumb_absolute_path') . $form['img_130_160_filename'];
        if ($this->Crop->loadImage($img_130_160_filename)) {
            $this->Crop->cropToDimensions($form['img_130_160_sx'], $form['img_130_160_sy'],$form['img_130_160_ex'],$form['img_130_160_ey']);
            $this->Crop->saveImage($img_130_160_filename);
            $this->Crop->flushImages();
        }
        $this->Session->setFlash('đã crop ảnh thành công', 'msg', array(), 'msg');
        $this->redirect(array('action' => 'index'));
    }
    function save() {
        $data = $this->data['Product'];

        //for upload thumbnail
        $this->Upload->setUploadpath(Configure::read('product_image_thumb_absolute_path'));
        $this->Upload->setRules('size', Configure::read('content_image_maxsize'));
        $this->Upload->setRules('ext', Configure::read('content_image_ext'));
        $row = $this->Product->findById($this->data['Product']['id']);

        //cal percent discount
        if(!empty ($data['price_promotion'])){
            $dis_count_price    =   $data['price'] - $data['price_promotion'];
            $data['price_promotion_percent']    = round($dis_count_price/$data['price'] * 100 );
        }else{
            $data['price_promotion_percent']    =   0;
        }
        //upload a small thumbnail (130x130)
        if ($this->data['Product']['thumbnail']['name'] != '') {
            if ($this->Upload->validate($this->data['Product']['thumbnail'])) {
                $data['thumbnail'] = $this->Upload->upload($this->data['Product']['thumbnail']);
                $this->Resize->run_resize(Configure::read('product_image_thumb_absolute_path').$data['thumbnail'], 130,130);

                //delete it
                if (is_file(Configure::read('product_image_thumb_absolute_path') . $row['Product']['thumbnail']) && $row['Product']['thumbnail'] != 'no_image.gif') {
                    $this->Upload->delete(Configure::read('product_image_thumb_absolute_path') . $row['Product']['thumbnail']);
                }
            } else {
                $this->Session->setFlash($this->Upload->getError(), 'error', array(), 'msg');
                $this->redirect(array('controller' => 'products', 'action' => 'index'));
                return;
            }
        } else {
            unset($data['thumbnail']);
            //delete image
            if (!empty($this->data['Product']['delete_small_thumbnail'])) {

                if (is_file(Configure::read('product_image_thumb_absolute_path') . $row['Product']['thumbnail']) && $row['Product']['thumbnail'] != 'no_image.gif') {
                    $this->Upload->delete(Configure::read('product_image_thumb_absolute_path') . $row['Product']['thumbnail']);
                    $data['thumbnail'] = 'no_image.gif';
                }
            }
        }

        //upload a large thumbnail 350x300
        if ($this->data['Product']['images']['name'] != '') {
            if ($this->Upload->validate($this->data['Product']['images'])) {
                $data['images'] = $this->Upload->upload($this->data['Product']['images']);
                $this->Resize->run_resize(Configure::read('product_image_thumb_absolute_path').$data['images'], 300,350);
                $image_smallsize_path   =   Configure::read('product_image_thumb_absolute_path').$data['images'];
                $this->Watermark->watermark_center($image_smallsize_path);
                //delete it
                if (is_file(Configure::read('product_image_thumb_absolute_path') . $row['Product']['images']) && $row['Product']['images'] != 'no_image.gif') {
                    $this->Upload->delete(Configure::read('product_image_thumb_absolute_path') . $row['Product']['images']);
                }
            } else {
                $this->Session->setFlash($this->Upload->getError(), 'error', array(), 'msg');
                $this->redirect(array('controller' => 'products', 'action' => 'index'));
                return;
            }
        } else {
            unset($data['images']);
            //delete image
            if (!empty($this->data['Product']['delete_image'])) {

                if (is_file(Configure::read('product_image_thumb_absolute_path') . $row['Product']['images']) && $row['Product']['images'] != 'no_image.gif') {
                    $this->Upload->delete(Configure::read('product_image_thumb_absolute_path') . $row['Product']['images']);
                    $data['images'] = 'no_image.gif';
                }
            }
        }

        //end upload thumbnail
        $data['alias'] = $this->Alias->alias($data['title']);
        if (empty($data['id'])) {
            //add watermark
            
            $data['ordering'] = $this->Product->nextOrder();
        }

        if ($this->Product->save($data)) {
            $this->Session->setFlash('lưu thành công thông tin', 'msg', array(), 'msg');
        } else {
            $this->Session->setFlash($this->Product->invalidFields(), 'error', array(), 'msg');
        }

        $this->redirect(array('controller' => 'products', 'action' => 'index'));
    }

    function cancel() {
        $this->redirect(array('controller' => 'products', 'action' => 'index'));
    }
    function promotion() {
        $cid = $this->params['form']['cid'];
        $conditions = array();
        foreach ($cid AS $id) {
            $conditions[] = array(
                'id' => $id,
                'is_promotion' => 1,
            );
        }

        if ($this->Product->saveAll($conditions)) {
            $this->Session->setFlash('lưu thành công thông tin', 'msg', array(), 'msg');
        } else {
            $this->Session->setFlash($this->Product->invalidFields(), 'error', array(), 'msg');
        }
        $this->redirect(array('controller' => 'products', 'action' => 'index'));
    }
    function unpromotion() {
        $cid = $this->params['form']['cid'];
        $conditions = array();
        foreach ($cid AS $id) {
            $conditions[] = array(
                'id' => $id,
                'is_promotion' => 0,
            );
        }

        if ($this->Product->saveAll($conditions)) {
            $this->Session->setFlash('lưu thành công thông tin', 'msg', array(), 'msg');
        } else {
            $this->Session->setFlash($this->Product->invalidFields(), 'error', array(), 'msg');
        }
        $this->redirect(array('controller' => 'products', 'action' => 'index'));
    }
    function published() {
        $cid = $this->params['form']['cid'];
        $conditions = array();
        foreach ($cid AS $id) {
            $conditions[] = array(
                'id' => $id,
                'published' => 1,
            );
        }

        if ($this->Product->saveAll($conditions)) {
            $this->Session->setFlash('lưu thành công thông tin', 'msg', array(), 'msg');
        } else {
            $this->Session->setFlash($this->Product->invalidFields(), 'error', array(), 'msg');
        }
        $this->redirect(array('controller' => 'products', 'action' => 'index'));
    }

    function unpublished() {
        $cid = $this->params['form']['cid'];
        $conditions = array();
        foreach ($cid AS $id) {
            $conditions[] = array(
                'id' => $id,
                'published' => 0,
            );
        }

        if ($this->Product->saveAll($conditions)) {
            $this->Session->setFlash('lưu thành công thông tin', 'msg', array(), 'msg');
        } else {
            $this->Session->setFlash($this->Product->invalidFields(), 'error', array(), 'msg');
        }
        $this->redirect(array('controller' => 'products', 'action' => 'index'));
    }

}

?>
